package com.atguigu.gmall.cart.filter;

import com.atguigu.gmall.cart.util.CartThreadLocalUtil;
import com.atguigu.gmall.cart.util.TokenUtil;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "cartFilter",urlPatterns = "/*")
@Order(1)
public class CartFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
      HttpServletRequest request1 =  (HttpServletRequest)request;
        String token = request1.getHeader("Authorization").replace("bearer ", "");
        Map<String, String> map = TokenUtil.dcodeToken(token);
        if (map != null ){
            String username = map.get("username");
            CartThreadLocalUtil.set(username);
        }
        chain.doFilter(request,response);
    }
}
